/*
 * @Author: your name
 * @Date: 2021-04-07 15:07:05
 * @LastEditTime: 2021-05-01 16:22:45
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \chronic-back-end\module\pushMod\controller.go
 */
package pushMod

import (
	"chronic/module/userMod"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type pushDto struct {
	Disease  string `form:"disease" json:"disease" binding:"required"`
	Sort     string `form:"sort" json:"sort" binding:"required"`
	Cover    string `form:"coverURL" json:"coverURL" binding:"required"`
	Title    string `form:"textTitle" json:"textTitle" binding:"required"`
	Picture1 string `form:"picture1URL" json:"picture1URL"`
	Text1    string `form:"passage1" json:"passage1"`
	Picture2 string `form:"picture2URL" json:"picture2URL"`
	Text2    string `form:"passage2" json:"passage2"`
	Text3    string `form:"passage3" json:"passage3"`
	AuthorID uint
}

func postOnePush(ctx *gin.Context) {
	user := ctx.MustGet("user").(userMod.User)
	var input pushDto
	if err := ctx.ShouldBind(&input); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	input.AuthorID = user.ID
	p, err := addOnePush(input)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}
	ctx.JSON(http.StatusOK, p)

}

func getPushes(ctx *gin.Context) {
	user := ctx.MustGet("user").(userMod.User)
	pushes, err := findPushesByDisease(user.Disease)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
	}
	ctx.JSON(http.StatusOK, pushes)
}

func getAllPushes(ctx *gin.Context) {
	pushes, err := findAllPushes()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err})
	} else {
		ctx.JSON(http.StatusOK, pushes)
	}
}

func adminDeletePush(ctx *gin.Context) {
	pushId := ctx.Query("id")
	id, _ := strconv.ParseUint(pushId, 10, 64)
	err := deletePush(uint(id))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err})
	} else {
		ctx.JSON(http.StatusOK, "删除成功！！")
	}
}

func getPushesByAuthorId(ctx *gin.Context) {
	authorId := ctx.Query("id")
	id, _ := strconv.ParseUint(authorId, 10, 64)
	pushes, err := findPushesByAuthorId(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": err})
	} else {
		ctx.JSON(http.StatusOK, pushes)
	}

}

func getPushesBySort(ctx *gin.Context) {
	condition := ctx.Query("condition")
	pushes, err := findPushesBySort(condition)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": err})
	} else {
		ctx.JSON(http.StatusOK, pushes)
	}
}
